﻿using System;

namespace App.Console
{
    public class Jacobi
    {
        public static void Solve(double[,] matrix, double[] coeficients)
        {
            System.Console.Clear();
            const int n = 4;
            const double tolerance = 0.000001d;

            const int maxIteractions = 1000;
            var iteractions = 0;

            var x0 = new double[n];
            var x = new double[n];
            var diff = new double[n];

            for (var i = 0; i < n; i++)
                diff[i] = 1;

            for (var iteration = 1; iteration <= maxIteractions; iteration++)
            {
                iteractions += 1;
                if (diff[0] <= tolerance && diff[1] <= tolerance && diff[2] <= tolerance && diff[3] <= tolerance)
                    break;

                for (var i = 0; i < n; i++)
                {
                    x[i] = coeficients[i];
                    for (var j = 0; j < n; j++)
                    {
                        if (j == i) continue;
                        x[i] -= matrix[i, j]*x0[j];
                    }
                    x[i] /= matrix[i, i];
                }

                for (var i = 0; i < n; i++)
                {
                    diff[i] = x[i] - x0[i];
                }

                Array.Copy(x, x0, n);
            }

            System.Console.WriteLine("O valor das variáveis é:\n");
            for (var i = 1; i <= n; i++)
            {
                System.Console.Write(" x{0} = {1:F5}", i, x[i - 1]);
                System.Console.WriteLine();
            }

            System.Console.WriteLine(iteractions);

            System.Console.Write("\nPressione enter para continuar...\n");
            System.Console.ReadKey();
        }
    }
}